<template>
  <div>
    <div id="logo" :class="{hideLogo: isShowForm}">
<!--      <div id="img"></div>-->
<!--      <video id="v1" autoplay loop muted>-->
<!--        <source src="../assets/login.mp4" type="video/mp4"  />-->
<!--      </video>-->
    </div>
<!--    <div ><a-button>点击</a-button></div>-->
    <div style="margin-top: 5%;" class="formed" :class="{ hideForm: !isShowForm, showForm: isShowForm }">
      <a-form :ref="formRef" :model="regData" v-bind="formItemLayout" @finish="handleRegister">
        <a-form-item label="用户名" name="username" :rules="[{ required: true, message: '请输入用户名' }, { validator: validateName, trigger: 'change' }, { validator: validateNameExist, trigger: 'submit' } ]" >
          <a-input v-model:value="regData.username" placeholder="最好是两个字的中文 排名显示时会比较好看"/>
        </a-form-item>
        <a-form-item label="邮箱" name="email" :rules="[{ type: 'email', message: '非法邮箱' }, { required: true, message: '请输入邮箱' }, { validator: validateEmailExist, trigger: 'submit' }]" >
          <a-input v-model:value="regData.email" />
        </a-form-item>
        <a-form-item has-feedback label="密码" name="password" :rules="[{ required: true, message: '请输入密码' }, { validator: validatePassLength, trigger: 'blur' }]" >
<!--          <a-input v-model:value="regData.password" type="password" autocomplete="off" />-->
          <a-input-password v-model:value="regData.password" autocomplete="off" />
        </a-form-item>
        <a-form-item has-feedback label="确认密码" name="confirm" :rules="[{ required: true, message: '请确认密码' }, { validator: validatePass, trigger: 'change' }]" >
<!--          <a-input v-model:value="regData.confirm" type="password" autocomplete="off" />-->
          <a-input-password v-model:value="regData.confirm" autocomplete="off" />
        </a-form-item>
        <a-form-item label="注册码" name="regCode" :rules="[{ required: true, message: '请输入注册码' }]">
          <a-input v-model:value="regData.regCode" />
        </a-form-item>
<!--        <a-form-item  label="验证码" :rules="[{ required: true }]">-->
<!--          <a-button @click="genRecaptcha" :type="recaptchaConf.type" :loading="recaptchaConf.isLoad">{{recaptchaConf.msg}}</a-button>-->
<!--        </a-form-item>-->
        <a-form-item v-bind="tailFormItemLayout" html-type="submit">
          <a-button :disabled="submitButtonStatus" type="primary" html-type="submit" size="default" ghost style="width:120px"><LoadingOutlined v-show="submitButtonStatus"/>注册</a-button>
        </a-form-item>
      </a-form>
    </div>
  </div>
</template>

<script lang="ts">
import { Form, Input, Button, message, notification } from 'ant-design-vue'
import type { FormInstance } from 'ant-design-vue'
import type { Rule } from 'ant-design-vue/es/form'
import { defineComponent, reactive, ref, onMounted, h } from 'vue'
import { register, checkRegisterField } from '@/service'
import { LoadingOutlined } from '@ant-design/icons-vue'

interface RegisterData {
  username: string,
  email: string,
  password: string,
  confirm: string,
  regCode: string
}

export default defineComponent({
  components: {
    LoadingOutlined,
    AForm: Form,
    AFormItem: Form.Item,
    AInput: Input,
    AButton: Button,
    AInputPassword: Input.Password
  },
  name: 'ARegister',
  setup () {
    // const router = useRouter()
    const formRef = ref<FormInstance>()
    const regData = reactive({
      username: '',
      email: '',
      password: '',
      confirm: '',
      regCode: ''
    })

    const validatePassLength = async (_rule: Rule, value: string) => {
      if (regData.password.length < 8) {
        return Promise.reject(new Error('密码不少于8位'))
      } else if (regData.password.length > 15) {
        return Promise.reject(new Error('密码不长于15位'))
      } else {
        return Promise.resolve()
      }
    }
    const validatePass = async (_rule: Rule, value: string) => {
      if (regData.password.length < 1) {
        return Promise.reject(new Error('请先输入密码'))
      } else if (value !== regData.password) {
        return Promise.reject(new Error('密码不一致'))
      } else {
        return Promise.resolve()
      }
    }

    const validateName = async () => {
      if (regData.username.length > 8) {
        return Promise.reject(new Error('名字太长啦'))
      }
      return Promise.resolve()
    }

    const validateNameExist = async (_rule: Rule, value: string) => {
      const data = new Map<string, string>()
      data.set('f', 'name')
      data.set('v', value)
      const ret = await checkRegisterField(data)
      if (ret.status === 200) {
        const d = ret.data
        if (d.data === true) {
          return Promise.reject(new Error('名字已经存在'))
        }
      }
      return Promise.resolve()
    }

    const validateEmailExist = async (_rule: Rule, value: string) => {
      const data = new Map<string, string>()
      data.set('f', 'email')
      data.set('v', value)
      const ret = await checkRegisterField(data)
      if (ret.status === 200) {
        const d = ret.data
        if (d.data === true) {
          return Promise.reject(new Error('邮箱已经存在'))
        }
      }
      return Promise.resolve()
    }

    const formItemLayout = {
      labelCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 3, offset: 2 },
        md: { span: 4, offset: 2 },
        xl: { span: 3, offset: 6 },
        xxl: { span: 4, offset: 5 }
      },
      wrapperCol: {
        xs: { span: 24, offset: 0 },
        sm: { span: 16 },
        md: { span: 15 },
        xl: { span: 10 },
        xxl: { span: 8 }
      }
    }

    const tailFormItemLayout = {
      wrapperCol: {
        xs: { span: 4, offset: 0 },
        sm: { span: 6, offset: 10 },
        md: { span: 6, offset: 12 },
        xl: { span: 4, offset: 13 },
        xxl: { span: 2, offset: 12 }
      }
    }

    // '邮件服务被 ban 了😭，无法使用激活邮件的方式。为了防止恶意注册，请关注公众号 csapp_go 发送【注册码】三个字，获取注册码。'
    const openNotification = () => {
      const key = `open${Date.now()}`
      notification.open({
        message: '温馨提示',
        description: h('div', [
          h('span', '邮件服务被 ban 了😭，无法使用激活邮件的方式。为了防止恶意注册，请关注公众号 csapp_go 也可以扫描二维码，发送【注册码】三个字，获取注册码。'),
          h('br'),
          h('img', { src: require('@/assets/wx.jpg'), alt: 'img', width: 120 })
        ]),
        duration: 60,
        btn: () =>
          h(
            Button,
            {
              type: 'primary',
              size: 'small',
              onClick: () => notification.close(key)
            },
            { default: () => '确认' }
          ),
        key,
        onClose: close
      })
    }

    onMounted(() => {
      setTimeout(openNotification, 1000)
    })

    return {
      formRef,
      regData,
      formItemLayout,
      tailFormItemLayout,
      validatePassLength,
      validatePass,
      validateName,
      validateNameExist,
      validateEmailExist
    }
  },
  data () {
    return {
      isShowForm: true,
      siteKey: '6LfPlUMfAAAAAHhWfftEvx-OxXMhSA7BOUvzEY9A',
      recaptchaConf: {
        isLoad: false,
        type: 'default',
        msg: '点击校验',
        lastComTime: 0
      },
      validateStatus: false,
      recaptchaToken: '',
      submitButtonStatus: false
    }
  },
  methods: {
    // genRecaptcha () {
    //   this.recaptchaConf.isLoad = true
    //   this.validateStatus = false
    //   this.recaptchaToken = ''
    //   const curTime = Math.round(new Date().getTime() / 1000)
    //   const t = this.recaptchaConf.lastComTime
    //   this.recaptchaConf.lastComTime = curTime
    //   if (this.recaptchaConf.lastComTime !== 0 && curTime - t <= 5) {
    //     this.recaptchaConf.msg = '通信忙'
    //     this.recaptchaConf.type = 'danger'
    //     const sleepTime = (Math.round(Math.random() * 6)) * 1000
    //     setTimeout(() => {
    //       this.recaptchaConf.isLoad = false
    //       this.recaptchaConf.msg = '重新验证'
    //       this.recaptchaConf.type = 'default'
    //     }, sleepTime)
    //     return
    //   }
    //   // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    //   // @ts-ignore
    //   // eslint-disable-next-line no-undef
    //   grecaptcha.ready(() => {
    //     // eslint-disable-next-line @typescript-eslint/ban-ts-comment
    //     // @ts-ignore
    //     // eslint-disable-next-line no-undef
    //     grecaptcha
    //       .execute(this.siteKey, { action: 'register' })
    //       .then((token: string | null | undefined) => {
    //         if (token !== undefined && token !== null) {
    //           this.recaptchaToken = token
    //           this.recaptchaConf.msg = '获取验证成功'
    //           this.recaptchaConf.type = 'primary'
    //           this.validateStatus = true
    //         } else {
    //           // this.recaptchaConf.type = 'danger'
    //           // this.recaptchaConf.msg = '验证失败'
    //         }
    //         this.recaptchaConf.isLoad = false
    //       })
    //       .catch((err: Error) => {
    //         message.error('校验出错，请稍后重试')
    //         console.log(err)
    //       })
    //   })
    // },
    handleRegister (value: RegisterData) {
      // if (this.recaptchaToken === '') {
      //   message.info('请点击校验')
      //   return
      // }
      const data = {
        name: value.username,
        passwd: value.password,
        email: value.email
      }
      const token: Map<string, string | number> = new Map<string, string | number>()
      // token.set('token', this.recaptchaToken)
      token.set('regCode', value.regCode)
      this.submitButtonStatus = true
      register(data, token)
        .then((response) => {
          if (response.status !== 200) {
            message.warn('请求失败')
            this.submitButtonStatus = false
            return
          }

          const resp = response.data

          if (resp.code !== 0) {
            message.warn('出错了')
            this.submitButtonStatus = false
            message.error(resp.msg)
            return
          }

          if (resp.data === true) {
            message.info('注册成功!')
            setTimeout(() => {
              this.$router.push({ name: 'login' })
            }, 1000)
          } else {
            message.error('出错了')
          }
          this.submitButtonStatus = false
        })
        .catch((err) => {
          message.error('未知出错')
          console.log(err)
          this.submitButtonStatus = false
        })
    }
  },
  created () {
    // const script = document.createElement('script')
    // script.src = 'https://www.recaptcha.net/recaptcha/api.js?render=' + this.siteKey
    // script.async = true
    // script.defer = true
    // script.id = 'recaptcha'
    // document.head.appendChild(script)
    document.body.style.backgroundColor = '#F5F5F5'
  },
  beforeUnmount () {
    document.body.style.backgroundColor = ''
  }
})
</script>

<style scoped>

  #logo {
    position: fixed;
    top: 0;
    left: 0;
    height: 100%;
    width: 100%;
    transition: width 4s, height 4s;
    -webkit-transition: width 4s, height 4s;
  }
  #img {
    background: url("../assets/logo-4.png") no-repeat center;
    background-size: 40%;
    height: 100%;
    width: auto;
    z-index: 2;
  }
  .hideLogo {
    display: None;
  }
  .dataForm {
    -webkit-transition: opacity 4s;
    transition: opacity 4s;
  }
  .showForm {
    display: block;
    opacity: 1;
  }
  .hideForm {
    display: None;
    opacity: 0;
  }
  video {
    position: fixed;
    top: 0;
    left: 0;
    height: auto;
    width: auto;
    z-index: -20;
  }
  @media screen and (max-width:500px){
    video {
      position: fixed;
      top: 0;
      left: 0;
      height: auto;
      width: auto;
      max-height: 100%;
      z-index: -20;
    }
  }
  @media screen and (max-width: 575px) {
    .formed {
      padding: 25px;
    }
  }
</style>
